package com.shop.flowershopmanager.controller;


import com.auth0.jwt.interfaces.DecodedJWT;
import com.shop.flowershopmanager.entity.User;
import com.shop.flowershopmanager.service.UserService;
import com.shop.flowershopmanager.utils.JWTUtils;
import com.shop.flowershopmanager.utils.R;
import com.shop.flowershopmanager.utils.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;


@RestController
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping("/user/login")
    public R<Object> login(User user) {
        log.info("用户名：{}", user.getName());
        log.info("password: {}", user.getPassword());

        Map<String, Object> map = new HashMap<>();
        Map<String, Object> mapUser = new HashMap<>();

        try {
            User userDB = userService.login(user);

            Map<String, String> payload = new HashMap<>();
            payload.put("id", userDB.getId());
            payload.put("name", userDB.getName());
            String token = JWTUtils.getToken(payload);
            map.put("token", token);
            map.put("id", userDB.getId());
            map.put("name", userDB.getName());

        } catch (Exception e) {
            e.printStackTrace();
            return R.failed(ResultCode.USER_LOGIN_ERROR);
        }
        return R.ok(map);
    }

    @PostMapping("/user/test")
    public Map<String, Object> test(HttpServletRequest request) {
        String token = request.getHeader("token");
        DecodedJWT verify = JWTUtils.verify(token);
        String id = verify.getClaim("id").asString();
        String name = verify.getClaim("name").asString();
        log.info("用户id：{}", id);
        log.info("用户名: {}", name);

        //TODO 业务逻辑
        Map<String, Object> map = new HashMap<>();
        map.put("state", true);
        map.put("msg", "请求成功");
        return map;
    }

}
